package br.com.iqt;

import br.com.iqt.util.Indenter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Arlino
 */
public class DriverWorkloadPostgresql implements DriverWorkload {
    private Dbms dbms;

    DriverWorkloadPostgresql(Dbms dbms) throws ClassNotFoundException {
        this.dbms = dbms;
        Class.forName(Dbms.driverPostgresql);
    }

    @Override
    public ArrayList getWorkLoad() throws ClassNotFoundException, SQLException {
        ArrayList workLoadList = new ArrayList();
        String user = dbms.getUser();
        String password = dbms.getPassword();
        String url = "jdbc:postgresql://" + dbms.getServer() + ":" + dbms.getPort() + "/" + dbms.getDatabase();
        String sql = "select pg_stat_get_backend_activity(s.backendid) as current_query "
                        + "from (select pg_stat_get_backend_idset() as backendid) as s";

        Connection connection = (Connection) DriverManager.getConnection(url, user, password);
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            String query = resultSet.getString("current_query");
            query = Indenter.removeWhiteSpace(Indenter.unindent(query));
            workLoadList.add(query);
        }
        connection.close();
        return workLoadList;
    }
}